package cn.anjubao.cp.api.config.security.filter;

import cn.anjubao.cp.api.config.security.UserToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SessionFilter extends OncePerRequestFilter {

    private static final String REGEX = "^(/.*)*(/user/login|/user/decode|/test(/.)*|/error)$";

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws ServletException, IOException {
        if (req.getRequestURI().matches(REGEX)) {
            chain.doFilter(req, res);
        } else {
            //UserToken userToken = new UserToken(req.getHeader("userCode"));
            //添加需要验证的头中
            UserToken userToken = new UserToken("userCode");
            SecurityContextHolder.getContext().setAuthentication(userToken);
            try {
                chain.doFilter(req, res);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
